<?php
class PressTrack
{
	function PressTrack() {
		mysql_connect('127.0.0.1', 'root', 'VNt3ks');
		mysql_query("SET CHARACTER SET 'utf8'"); 	
		mysql_query("SET NAMES 'utf8'");
		mysql_select_db('press_track_new');				
    }
		
	function insertUser($user, $pass, $name, $section) {
		$salt = $this->generateSalt();
		$sql = sprintf("INSERT INTO press_track_new.user (nick, pass, name, section, salt) VALUES ('%s', '%s', '%s', %d, '%s')", $user, md5(md5($pass).$salt), $name, $section, $salt);
		$query = mysql_query($sql);
		if (mysql_errno()) return mysql_errno() . ": " . mysql_error();
		return "ok";
	}
	
	private function generateSalt() {
		$salt = '';
		$length = rand(5,10); 
		for($i=0; $i<$length; $i++) {
			$salt .= chr(rand(33,126)); 
		}
		return $salt;
	}
		
	function loginUser($user, $pass, $sec) {
		$sql = $this->escape("SELECT iduser, pass, salt FROM press_track_new.user WHERE nick = '$user' AND section = '$sec'");
		$query = mysql_query($sql);
		$rs = mysql_fetch_object($query);
		if ($rs->pass == md5(md5($pass).$rs->salt))
			return $rs->iduser;
		else false;
	}
	
	private function escape($sql) {
		$args = func_get_args();
		foreach($args as $key => $val) {
			$args[$key] = mysql_real_escape_string($val);
		}
		$args[0] = $sql;
		return call_user_func_array('sprintf', $args);
	}
		
	// GET
	
	function getNextOrderLabel() {
		$year = date('Y');
		//$sql = sprintf("select max(press_track_new.order.label)as val from press_track_new.order where LOCATE('%s', press_track_new.order.creation, 6)", $year);
		$sql = sprintf("SELECT press_track_new.order.label as val FROM press_track_new.order WHERE LOCATE('%s', press_track_new.order.creation, 6)", $year);
		$query = mysql_query($sql);
		$ar = array();
		while ($row = mysql_fetch_object($query)) {
			$ar[] = (int)$row->val;
		}
		$len = count($ar);
		for ($i=1; $i < $len + 1; $i++) {
			if (! in_array($i, $ar)) break;
		}
      	return $i;
	}

	function getData($manager_id, $table) {
		$ArrayOfData = array();
		switch ($table)
		{
			case "manager":
			{
				$sql = sprintf("SELECT * FROM press_track_new.user WHERE medium = -1 AND section = 1 ORDER BY name");
			} break;
			case "customer":
			{
				$sql = "SELECT * FROM press_track_new.user WHERE press_track_new.user.medium = $manager_id ORDER BY name";
			} break;
			case "cur_order":
			{
				$sql = "SELECT * FROM press_track_new.order WHERE press_track_new.order.manager = $manager_id AND press_track_new.order.state != 4";
			} break;
			case "order":
			{
				$sql = "SELECT * FROM press_track_new.order WHERE press_track_new.order.manager = $manager_id  AND press_track_new.order.state = 4";
			} break;
			case "product":
			{
				$sql = "SELECT * FROM press_track_new.order WHERE press_track_new.order.manager = $manager_id";
				$query = mysql_query($sql);
				$ArrayOfData = array();
				while ($row = mysql_fetch_object($query)) 
				{
					$sql = "SELECT * FROM press_track_new.product WHERE press_track_new.product.order = $row->idorder";
					$query2 = mysql_query($sql);
					while ($row2 = mysql_fetch_object($query2)) 
					{
						$ArrayOfData[] = $row2;
					}
				}
				return $ArrayOfData;
			}break;
			case "task":
			{
				$sql = "SELECT * FROM press_track_new.order WHERE press_track_new.order.manager = $manager_id";
				$query = mysql_query($sql);
				$ArrayOfData = array();
				while ($row = mysql_fetch_object($query)) 
				{
					$sql = "SELECT * FROM press_track_new.task WHERE press_track_new.task.order = $row->idorder";
					$query2 = mysql_query($sql);
					while ($row2 = mysql_fetch_object($query2)) 
					{
						$ArrayOfData[] = $row2;
					}
				}
				return $ArrayOfData;
			}break;
			case "relation":
			{
				$sql = "SELECT * FROM press_track_new.relation WHERE press_track_new.relation.product_id IN  (
				SELECT idproduct FROM press_track_new.product WHERE press_track_new.product.order IN (
				SELECT idorder FROM press_track_new.order WHERE press_track_new.order.manager = $manager_id))";
				$query = mysql_query($sql);
				while ($row = mysql_fetch_object($query)) 
				{
					$ArrayOfData[] = $row;
				}
				return $ArrayOfData;
			}break;
			case "payment":
			{
				$sql = "SELECT *, label, name FROM press_track_new.payment, press_track_new.order, press_track_new.user WHERE press_track_new.order.idorder = press_track_new.payment.order AND press_track_new.payment.manager = $manager_id AND press_track_new.user.iduser = press_track_new.payment.customer";
			} break;
			case "year":
			{
				$sql = "SELECT DISTINCT creation as label FROM press_track_new.order WHERE press_track_new.order.creation != ''";
			}break;
			case "delivery":
			{
				$sql = "SELECT *, label, thick, size FROM press_track_new.delivery, press_track_new.paper WHERE press_track_new.paper.idpaper = press_track_new.delivery.paper";
			}break;
			case "supplier":
			{
				$sql = "SELECT DISTINCT supplier as label FROM press_track_new.delivery WHERE LENGTH(supplier) > 0 AND supplier != 'Коррекция +' ORDER BY label";
			}break;
			case "payer":
			{
				$sql = "SELECT DISTINCT payer as label FROM press_track_new.delivery WHERE LENGTH(payer) > 0 AND payer != 'Коррекция +' ORDER BY label";
			}break;
			case "issue":
			{
				$sql = "SELECT *, 
				press_track_new.issue.idissue as idissue,
				press_track_new.issue.paper as paper,
				press_track_new.issue.num as num,
				press_track_new.issue.cost as cost,
				press_track_new.issue.creation as creation,
				press_track_new.issue.request as request,
				press_track_new.issue.label as label,
				press_track_new.paper.label as paper_label, 
				press_track_new.paper.thick as paper_thick, 
				press_track_new.paper.size as paper_size 
				FROM press_track_new.issue, press_track_new.paper WHERE press_track_new.paper.idpaper = press_track_new.issue.paper";
				
				$query = mysql_query($sql);
				if (mysql_errno()) return mysql_errno() . ": " . mysql_error();
		
				while ($row = mysql_fetch_object($query)) 
				{
					if ($row->request != null) {
						$sql = "SELECT press_track_new.user.name as customer FROM press_track_new.user 
							WHERE iduser = (SELECT press_track_new.order.customer FROM press_track_new.order 
							WHERE idorder = (SELECT press_track_new.task.order as idorder FROM press_track_new.task 
							WHERE press_track_new.task.idtask = $row->request))";
							$query2 = mysql_query($sql);
						$cust = mysql_fetch_object($query2);
						$row->customer = $cust->customer;
					}
					$ArrayOfData[] = $row;
				}
				return $ArrayOfData;
				
			}break;
			case 'factor':
			{
				$sql = "SELECT * FROM press_track_new.factor";
				$query = mysql_query($sql);
				while ($row = mysql_fetch_object($query)) 
				{
					$row->ar_value = explode(",", $row->value);
					$len = count($row->ar_value);
					for ($i=0; $i < $len; $i++)
					{
						$row->ar_value[$i] = trim($row->ar_value[$i]);
					}
					$ArrayOfData[] = $row;
				}
				return $ArrayOfData;				
			}break;
			case 'paper':
			{
				$sql = "SELECT * FROM press_track_new.paper ORDER BY label, thick";
			}break;
			case 'user_name':
			{
				$sql = sprintf("SELECT name as val FROM press_track_new.user WHERE iduser = %d", $manager_id);
				$query = mysql_query($sql);
				$row = mysql_fetch_object($query);
				return $row->val;
			}break;
			default:
			{
				$sql = "SELECT * FROM press_track_new." . $table;
			}
		}

		$query = mysql_query($sql);
		
		if (mysql_errno()) return mysql_errno() . ": " . mysql_error();
		
		while ($row = mysql_fetch_object($query)) 
      	{
			$ArrayOfData[] = $row;
	  	}
		return $ArrayOfData;
	}
	
	function getProductByOrder($manager_id, $order) {
		$sql = "SELECT * FROM press_track_new.product WHERE press_track_new.product.order = $order";
		$query = mysql_query($sql);
		
		if (mysql_errno()) return mysql_errno() . ": " . mysql_error();
		
		while ($row = mysql_fetch_object($query)) 
			$ArrayOfData[] = $row;
	  	
		return $ArrayOfData;
	}
	
	function getTaskByOrder($manager_id, $order) {
		$sql = "SELECT * FROM press_track_new.task WHERE press_track_new.task.order = $order";
		$query = mysql_query($sql);
		
		if (mysql_errno()) return mysql_errno() . ": " . mysql_error();
		
		while ($row = mysql_fetch_object($query)) 
			$ArrayOfData[] = $row;
	  	
		return $ArrayOfData;
	}
	
	function getRelationByOrder($manager_id, $order) {
		$sql 		= "SELECT * FROM press_track_new.relation WHERE press_track_new.relation.product_id IN (SELECT idproduct FROM press_track_new.product WHERE press_track_new.product.order = $order)";
		$query		= mysql_query($sql);
		
		if (mysql_errno()) return mysql_errno() . ": " . mysql_error();
		
		while ($row = mysql_fetch_object($query)) 
			$ArrayOfData[] = $row;
		
		return $ArrayOfData;
	}
	
	function getStoreOrder($manager_id, $year) {
		$sql = "SELECT * FROM press_track_new.order WHERE LOCATE($year, press_track_new.order.creation, 6) AND press_track_new.order.manager = $manager_id  AND press_track_new.order.state = 4";
		$query = mysql_query($sql);
		
		if (mysql_errno()) return mysql_errno() . ": " . mysql_error();
		
		while ($row = mysql_fetch_object($query)) 
      	{
			$ArrayOfData[] = $row;
	  	}
		return $ArrayOfData;
	}
	
	function getProductIdFromRelation($idtask) {
		$sql = "SELECT product_id FROM press_track_new.relation WHERE press_track_new.relation.task_id = $idtask"; 
		$query = mysql_query($sql);
		
		while ($row = mysql_fetch_object($query)) 
			$ArrayOfData[] = $row;
	  	
		return $ArrayOfData;
	}
	
	function getPaperRequest($table) {
		switch ($table)
		{
			case "cur_request":
			{
				$sql = "SELECT *, name FROM press_track_new.order, press_track_new.user WHERE press_track_new.order.state != 4 AND press_track_new.order.state != 8 AND press_track_new.user.iduser = press_track_new.order.manager ORDER BY manager";
			}break;
			case "all_request":
			{
				$sql = "SELECT *, name FROM press_track_new.order, press_track_new.user WHERE LOCATE('2011', press_track_new.order.creation, 6) AND press_track_new.user.iduser = press_track_new.order.manager AND press_track_new.order.state != 8 ORDER BY manager";
			}break;
		}
		
		$query = mysql_query($sql);
		if (mysql_errno()) return mysql_errno() . ": " . mysql_error();
		
		while ($order = mysql_fetch_object($query)) 
		{
			if ($table == "cur_request")
				$sql = "SELECT * FROM press_track_new.task WHERE press_track_new.task.order = $order->idorder AND press_track_new.task.label = 'бумага' AND press_track_new.task.state IN(1,6)";
			else if ($table == "all_request")
				$sql = "SELECT * FROM press_track_new.task WHERE press_track_new.task.order = $order->idorder AND press_track_new.task.label = 'бумага' AND press_track_new.task.state != 1 AND press_track_new.task.state != 6";
			$query2 = mysql_query($sql);
			
			while ($paper = mysql_fetch_object($query2)) 
			{
				$order_copy = clone $order;
				$order_copy->paper = $paper;
				
				$paper_parts = explode("\r", $order_copy->paper->value);
				$order_copy->paper->paper_label = trim(str_replace("название : ", "", $paper_parts[0]));
				$order_copy->paper->paper_thick = trim(str_replace("плотность : ", "", $paper_parts[1]));
				$order_copy->paper->paper_size = trim(str_replace("формат : ", "", $paper_parts[2]));
				$order_copy->paper->paper_cut = trim(str_replace("доля резки : ", "", $paper_parts[3]));
				$order_copy->paper->is_customer = trim(str_replace("заказчика : ", "", $paper_parts[4]));
				 
				$sql = "SELECT product_id as product_id FROM press_track_new.relation WHERE press_track_new.relation.task_id = $paper->idtask LIMIT 1";
				$query3 = mysql_query($sql);
				$res = mysql_fetch_object($query3);
				
				if ($order_copy->group_num > 1)
				{
					$sql = "SELECT * FROM press_track_new.product WHERE idproduct = $res->product_id";
					$query_pr = mysql_query($sql);
					$res_product = mysql_fetch_object($query_pr);
					$order_copy->label = $order_copy->label . '-' . $res_product->group;
				}
				
				$sql = "SELECT task_id as task_id FROM press_track_new.relation WHERE press_track_new.relation.product_id = $res->product_id";
				$query3 = mysql_query($sql);
												
				while ($task = mysql_fetch_object($query3)) 
				{
					$sql = "SELECT * FROM press_track_new.task WHERE press_track_new.task.idtask = $task->task_id AND press_track_new.task.label = 'печать' LIMIT 1";
					$query4 = mysql_query($sql);
					while ($press = mysql_fetch_object($query4)) 
					{
						$order_copy->press = $press;
						$press_parts = explode("\r", $order_copy->press->value);
						$order_copy->press->press_label = trim(str_replace("машина : ", "", $press_parts[0]));
						$order_copy->press->press_run = trim(str_replace("тираж : ", "", $press_parts[1]));
						$order_copy->press->press_waste = trim(str_replace("на приладку : ", "", $press_parts[2]));
						$order_copy->press->press_sheet = trim(str_replace("формат печати : ", "", $press_parts[3]));
						$order_copy->press->press_color = trim(str_replace("красочность : ", "", $press_parts[4]));
					}
				}	
				
				if ($order_copy->customer != NULL && $order_copy->customer != '?')
				{
					$sql = "SELECT name as cust_label FROM press_track_new.user WHERE press_track_new.user.iduser = $order_copy->customer";
					$query_cust = mysql_query($sql);
					if (mysql_errno()) return mysql_errno() . ": " . mysql_error();
				
					while ($cust = mysql_fetch_object($query_cust)) 
					{
						$order_copy->customer_label = $cust->cust_label;
					}
				}					
				
				$order_copy->total = 0;
				
				$ArrayOfData[] = $order_copy;
			}			
		}		
		return $ArrayOfData;
	}
	
	// INSERT
	
	function insertCustomer($name, $contact, $medium) {
		$sql = sprintf("INSERT INTO press_track_new.user (name, contact, section, medium) VALUES ('%s', '%s', %d, %d)", $name, $contact, 7, $medium);
		$query = mysql_query($sql);
		$cust_id = mysql_insert_id(); 
		if (mysql_errno()) return mysql_errno() . ": " . mysql_error();
		else return $cust_id;
	}

	function insertOrder($creation, $manager) {
		$sql = sprintf("INSERT INTO press_track_new.order (label, group_num, creation, state, manager) VALUES (%d, %d, '%s', %d, %d)", 0, 1, $creation, 1, $manager);
		$query = mysql_query($sql);
		if (mysql_errno()) return mysql_errno() . ": " . mysql_error();
		$idorder 	= mysql_insert_id();
		
		$sql 		= sprintf("INSERT INTO press_track_new.product (press_track_new.product.group, press_track_new.product.order) VALUES (%d, %d)", 1, $idorder);
		$query 	= mysql_query($sql);
		if (mysql_errno()) return mysql_errno() . ": " . mysql_error();
		$idproduct 	= mysql_insert_id();

		$task['label']	= 'печать';
		$task['value']	= 'машина : SM-74\rтираж : 1000\rна приладку : 100\rформат печати : 500x350\rкрасочность : 4+4';
		$task['section']	= 4;
		$task['state']	= 1;
		$sql 		= sprintf("INSERT INTO press_track_new.task (press_track_new.task.label, press_track_new.task.value, press_track_new.task.section, press_track_new.task.state, press_track_new.task.order) VALUES ('%s', '%s', %d, %d, %d)", $task['label'], $task['value'], $task['section'], $task['state'], $idorder); 
		$query 	= mysql_query($sql);
		if (mysql_errno()) return mysql_errno() . ": " . mysql_error();
		$idtask 	= mysql_insert_id();

		$sql = sprintf("INSERT INTO press_track_new.relation (press_track_new.relation.task_id, press_track_new.relation.product_id) VALUES (%d, %d)", $idtask, $idproduct); 
		$query = mysql_query($sql);

		$task['label']	= 'бумага';
		$task['value']	= 'название : Art\rплотность : no set\rформат : set\rдоля резки : set\rзаказчика : set';
		$task['section']	= 2;
		$task['state']	= 1;
		$sql 		= sprintf("INSERT INTO press_track_new.task (press_track_new.task.label, press_track_new.task.value, press_track_new.task.section, press_track_new.task.state, press_track_new.task.order) VALUES ('%s', '%s', %d, %d, %d)", $task['label'], $task['value'], $task['section'], $task['state'], $idorder); 
		$query 	= mysql_query($sql);
		if (mysql_errno()) return mysql_errno() . ": " . mysql_error();
		$idtask 	= mysql_insert_id();

		$sql = sprintf("INSERT INTO press_track_new.relation (press_track_new.relation.task_id, press_track_new.relation.product_id) VALUES (%d, %d)", $idtask, $idproduct); 
		$query = mysql_query($sql);
		
		//$sql = sprintf("INSERT INTO press_track_new.payment (press_track_new.payment.order, press_track_new.payment.manager, press_track_new.payment.customer, press_track_new.payment.sum) VALUES (%d, %d, %d, %s)", $idorder, $manager, 1, 50); 
		//$query = mysql_query($sql);

		return $idorder;
	}
	
	function insertProduct($idorder, $group) {
		$sql 		= sprintf("INSERT INTO press_track_new.product (press_track_new.product.group, press_track_new.product.order) VALUES (%d, %d)", $group, $idorder);
		$query 		= mysql_query($sql);
		if (mysql_errno()) return mysql_errno() . ": " . mysql_error();
		return mysql_insert_id();
	}
	
	function insertTask($label, $value, $section, $order) {
		$sql = sprintf("INSERT INTO press_track_new.task (press_track_new.task.label, press_track_new.task.value, press_track_new.task.section, press_track_new.task.order) VALUES ('%s', '%s', %d, %d)", $label, $value, $section, $order); 
		$query = mysql_query($sql);
		if (mysql_errno()) return mysql_errno() . ": " . mysql_error();
		else return mysql_insert_id();
	}

	function insertRelation($idtask, $idproduct) {
		$sql = sprintf("INSERT INTO press_track_new.relation (press_track_new.relation.task_id, press_track_new.relation.product_id) VALUES (%d, %d)", $idtask, $idproduct); 
		$query = mysql_query($sql);
		if (mysql_errno()) return mysql_errno() . ": " . mysql_error();
		else return mysql_insert_id();
	}
	
	function addOrderGroup($idorder, $group) {
		$sql	= sprintf("INSERT INTO press_track_new.product (press_track_new.product.group, press_track_new.product.order) VALUES (%d, %d)", $group, $idorder);
		$query 	= mysql_query($sql);
		if (mysql_errno()) return mysql_errno() . ": " . mysql_error();
		$idproduct 	= mysql_insert_id();

		$task['label']	= 'печать';
		$task['value']	= 'машина : SM-74\rтираж : 1000\rна приладку : 100\rформат печати : 500x350\rкрасочность : 4+4';
		$task['section']	= 4;
		$task['state']	= 1;
		$sql 		= sprintf("INSERT INTO press_track_new.task (press_track_new.task.label, press_track_new.task.value, press_track_new.task.section, press_track_new.task.state, press_track_new.task.order) VALUES ('%s', '%s', %d, %d, %d)", $task['label'], $task['value'], $task['section'], $task['state'], $idorder); 
		$query 	= mysql_query($sql);
		if (mysql_errno()) return mysql_errno() . ": " . mysql_error();
		$idtask 	= mysql_insert_id();

		$sql = sprintf("INSERT INTO press_track_new.relation (press_track_new.relation.task_id, press_track_new.relation.product_id) VALUES (%d, %d)", $idtask, $idproduct); 
		$query = mysql_query($sql);

		$task['label']	= 'бумага';
		$task['value']	= 'название : Art\rплотность : no set\rформат : set\rдоля резки : set\rзаказчика : set';
		$task['section']	= 2;
		$task['state']	= 1;
		$sql 		= sprintf("INSERT INTO press_track_new.task (press_track_new.task.label, press_track_new.task.value, press_track_new.task.section, press_track_new.task.state, press_track_new.task.order) VALUES ('%s', '%s', %d, %d, %d)", $task['label'], $task['value'], $task['section'], $task['state'], $idorder); 
		$query 	= mysql_query($sql);
		if (mysql_errno()) return mysql_errno() . ": " . mysql_error();
		$idtask 	= mysql_insert_id();

		$sql = sprintf("INSERT INTO press_track_new.relation (press_track_new.relation.task_id, press_track_new.relation.product_id) VALUES (%d, %d)", $idtask, $idproduct); 
		$query = mysql_query($sql);

		return $idorder;
	}		
	
	function insertOperation($label, $section) {
		$sql = sprintf("INSERT INTO operation (label, section) VALUES ('%s', '%d')", $label, $section);
		$query = mysql_query($sql);
		$operation_id = mysql_insert_id(); 
		if (mysql_errno()) return mysql_errno() . ": " . mysql_error();
		return $operation_id;
	}

	function insertFactor($f) {
		$sql = sprintf("INSERT INTO press_track_new.factor (press_track_new.factor.label, press_track_new.factor.value, press_track_new.factor.operation) VALUES ('%s', '%s', %d)", $f->label, $f->value, $f->operation);
		$query = mysql_query($sql);
		$factor_id = mysql_insert_id(); 
		if (mysql_errno()) return mysql_errno() . ": " . mysql_error();
		return $factor_id;
	}	
	
	function insertDelivery($invoice, $creation, $paper_label, $paper_thick, $paper_size, $paper_num, $supplier, $payer, $sum, $exch) {
		$sql = sprintf("SELECT idpaper as val FROM press_track_new.paper WHERE press_track_new.paper.label = '%s' AND press_track_new.paper.thick = %d AND press_track_new.paper.size = '%s'", $paper_label, $paper_thick, $paper_size);
		$query = mysql_query($sql);
		 
		if ( mysql_num_rows($query) == 0)
		{
			$sql = sprintf("INSERT INTO press_track_new.paper (press_track_new.paper.label, press_track_new.paper.thick, press_track_new.paper.size, press_track_new.paper.cost, press_track_new.paper.total) VALUES ('%s', %d, '%s', %d, %d)", $paper_label, $paper_thick, $paper_size, ($sum / $paper_num) * $exch, 0);
			$query = mysql_query($sql);
			$res->val = mysql_insert_id();					
		}
		else
		{
			$res = mysql_fetch_object($query);			
		}
			
		$sql = sprintf("INSERT INTO press_track_new.delivery (press_track_new.delivery.invoice, press_track_new.delivery.creation, press_track_new.delivery.num, press_track_new.delivery.supplier, press_track_new.delivery.payer, press_track_new.delivery.sum, press_track_new.delivery.paper) VALUES ('%s', '%s', %d, '%s', '%s', %d, %d)", $invoice, $creation, $paper_num, $supplier, $payer, $sum, $res->val);
		$query = mysql_query($sql);
		$iddelivery = mysql_insert_id();
		//if ($sum > 0) {
			$sql = "UPDATE press_track_new.paper SET press_track_new.paper.total = press_track_new.paper.total + $paper_num WHERE press_track_new.paper.idpaper = $res->val";
			$query = mysql_query($sql);
		//}
		if (mysql_errno()) return mysql_errno() . ": " . mysql_error();
		return $iddelivery;
	}
	
	function insertIssue($paper, $num, $cost, $creation, $request, $label) {
		$sql = sprintf("INSERT INTO press_track_new.issue (press_track_new.issue.paper, press_track_new.issue.num, press_track_new.issue.cost, press_track_new.issue.creation, press_track_new.issue.request, press_track_new.issue.label) VALUES (%d, %d, %d, '%s', %d, '%s')", $paper, $num, $cost, $creation, $request, $label);
		$query = mysql_query($sql);
		$idissue = mysql_insert_id(); 
		if (mysql_errno()) return mysql_errno() . ": " . mysql_error();
		return $idissue;
	}
	
	function copyOrder($id, $creation) {
		$sql = sprintf("SELECT label, group_num, note, price, manager, customer FROM press_track_new.order WHERE press_track_new.order.idorder = %d", $id);
		$query = mysql_query($sql);
		if (mysql_errno()) return mysql_errno() . ": " . mysql_error();
		$res = mysql_fetch_object($query);
		$res->note = $res->note . "Повтор заказа № " . $res->label;
		
		$sql = sprintf("INSERT INTO press_track_new.order (label, creation, state, group_num, note, price, manager, customer) VALUES (%d, '%s', %d, %d, '%s', %d, %d, %d)", 0, $creation, 1, $res->group_num, $res->note, $res->price, $res->manager, $res->customer);
		$query = mysql_query($sql);
		if (mysql_errno()) return mysql_errno() . ": " . mysql_error();
		$idorder = mysql_insert_id();	
		
		$rel_ar = array(); // архив для связей между изделиями и заданиями 
		
		// копирование изделий
		$sql = sprintf("SELECT * FROM press_track_new.product WHERE press_track_new.product.order = %d", $id);
		$query = mysql_query($sql);
		if (mysql_errno()) return mysql_errno() . ": " . mysql_error();
		
		while ($product = mysql_fetch_object($query)) 
		{
			$sql 		= sprintf("INSERT INTO press_track_new.product (press_track_new.product.label, press_track_new.product.run, press_track_new.product.size, press_track_new.product.color, press_track_new.product.group, press_track_new.product.order) VALUES ('%s', %d, '%s', '%s', %d, %d)", $product->label, $product->run, $product->size, $product->color, $product->group, $idorder);
			$query2		= mysql_query($sql);
			if (mysql_errno()) return mysql_errno() . ": " . mysql_error();
			$idproduct 	= mysql_insert_id();
			
			$sql = sprintf("SELECT * FROM press_track_new.relation WHERE product_id = %d", $product->idproduct);
			$query3 = mysql_query($sql);
			if (mysql_errno()) return mysql_errno() . ": " . mysql_error();
			
			while ($rel = mysql_fetch_object($query3)) 
			{
				$rel->product_id = $idproduct;
				$rel_ar[] = $rel;
			}		
		}
		
		// копирование заданий
		$sql = sprintf("SELECT * FROM press_track_new.task WHERE press_track_new.task.order = %d", $id);
		$query4 = mysql_query($sql);
		if (mysql_errno()) return mysql_errno() . ": " . mysql_error();
		
		while ($task = mysql_fetch_object($query4)) 
		{
			$sql 		= sprintf("INSERT INTO press_track_new.task (press_track_new.task.label, press_track_new.task.value, press_track_new.task.section, press_track_new.task.execute, press_track_new.task.cost, press_track_new.task.order) VALUES ('%s', '%s', %d, '%s', %d, %d)", $task->label, $task->value, $task->section, $task->execute, $task->cost, $idorder);
			$query2		= mysql_query($sql);
			if (mysql_errno()) return mysql_errno() . ": " . mysql_error();
			$idtask 	= mysql_insert_id();
			
			foreach ($rel_ar as $rel)
			{
				if ($rel->task_id == $task->idtask)
				{
					$sql 		= sprintf("INSERT INTO press_track_new.relation (product_id, task_id) VALUES (%d, %d)", $rel->product_id, $idtask);
					$query3		= mysql_query($sql);
					if (mysql_errno()) return mysql_errno() . ": " . mysql_error();
				}
			}		
		}
		
		return $idorder;
	}
	
	// UPDATE
	
	function updateCustomer($iduser, $name, $contact) {
		$sql = sprintf("UPDATE press_track_new.user SET press_track_new.user.name = '%s', press_track_new.user.contact = '%s' WHERE iduser = %d", $name, $contact, $iduser);
		$query = mysql_query($sql);
		if (mysql_errno()) return mysql_errno() . ": " . mysql_error();
		else return "successful";
	}

	function updateOrder($idorder, $param, $value) {
		if ($param == "customer" || $param =="group_num" || $param =="state" || $param =="label")
		{
			$sql = sprintf("UPDATE press_track_new.order SET %s = %d WHERE idorder = %d", $param, $value, $idorder);
			
			if ($param == "state" && $value == 9)
			{
				$sql2 = sprintf("UPDATE press_track_new.task SET state = 8 WHERE press_track_new.task.order = %d", $idorder);
				$query2 = mysql_query($sql2);
				if (mysql_errno()) return mysql_errno() . ": " . mysql_error();
			}			
			else if ($param == "state" && $value == 1)
			{
				$sql2 = sprintf("UPDATE press_track_new.task SET state = 1 WHERE press_track_new.task.order = %d", $idorder);
				$query2 = mysql_query($sql2);
				if (mysql_errno()) return mysql_errno() . ": " . mysql_error();
			}
		}
		else
		{
			$sql = sprintf("UPDATE press_track_new.order SET %s = '%s' WHERE idorder = %d", $param, $value, $idorder);
		}
		$query = mysql_query($sql);
		if (mysql_errno()) return mysql_errno() . ": " . mysql_error();
		else return "successful";
	}
	
	function updateTask($idtask, $value) {
		$sql = sprintf("UPDATE press_track_new.task SET value = '%s' WHERE idtask = %d", $value, $idtask);
		$query = mysql_query($sql);
		if (mysql_errno()) return mysql_errno() . ": " . mysql_error();
		else return "successful";
	}
	
	function updateTaskParam ($idtask, $param, $value, $section) {
		if ($param == "cost")
		{
			$sql = sprintf("UPDATE press_track_new.task SET %s = %d WHERE idtask = %d", $param, $value, $idtask);
			$query = mysql_query($sql);
			
			$sql = sprintf("SELECT press_track_new.task.order as val FROM press_track_new.task WHERE idtask = %d", $idtask);
			$query = mysql_query($sql);
			$res = mysql_fetch_object($query);
			
			$sql = sprintf("SELECT SUM(cost) as val FROM press_track_new.task WHERE press_track_new.task.order = %d", $res->val);
			$query = mysql_query($sql);
			$res2 = mysql_fetch_object($query);
			
			$sql = sprintf("UPDATE press_track_new.order SET press_track_new.order.price = %d WHERE press_track_new.order.idorder = %d", $res2->val, $res->val);
			$query = mysql_query($sql);
		}
		else
		{
			$sql = sprintf("UPDATE press_track_new.task SET %s = '%s' WHERE idtask = %d", $param, $value, $idtask);
			$query = mysql_query($sql);
		}
		
		if (mysql_errno()) return mysql_errno() . ": " . mysql_error();
		
		if ($section == 1) {
			$sql = sprintf("UPDATE press_track_new.task SET state = %d WHERE idtask = %d AND state != 1", '6', $idtask);
			$query = mysql_query($sql);
		}
		
		if (mysql_errno()) return mysql_errno() . ": " . mysql_error();
		else return "successful";
	}

	function updateProduct($idproduct, $param, $value) {
		switch ($param)
		{
			case "run":
			$sql = sprintf("UPDATE press_track_new.product SET run = %d WHERE idproduct = %d", $value, $idproduct);
			break;
			case "label":
			case "size":
			case "color":
			$sql = sprintf("UPDATE press_track_new.product SET %s = '%s' WHERE idproduct = %d", $param, $value, $idproduct);
			break;
		}

		$query = mysql_query($sql);
		if (mysql_errno()) return mysql_errno() . ": " . mysql_error();
		else return "successful";
	}
	
	function updatePaper($idpaper, $param, $value) {
		if ($param == "cost" || $param == "thick")
		{
			$sql = sprintf("UPDATE press_track_new.paper SET %s = %f WHERE idpaper = %d", $param, $value, $idpaper);
		}
		else if ($param == "total")
		{
			$sql = sprintf("UPDATE press_track_new.paper SET press_track_new.paper.total = %d WHERE idpaper = %d", $value, $idpaper);
		}
		else
		{
			$sql = sprintf("UPDATE press_track_new.paper SET %s = '%s' WHERE idpaper = %d", $param, $value, $idpaper);
		}
		$query = mysql_query($sql);
		if (mysql_errno()) return mysql_errno() . ": " . mysql_error();
		else return "successful";	
	}
	
	function correctPaper($idpaper, $total, $value, $label, $creation, $mode) {
		$sql = sprintf("UPDATE press_track_new.paper SET press_track_new.paper.total = %d WHERE idpaper = %d", $total, $idpaper);
		$query = mysql_query($sql);
		if (mysql_errno()) return mysql_errno() . ": " . mysql_error();
		
		if ($mode == "-")
			$sql = sprintf("INSERT INTO press_track_new.issue (press_track_new.issue.paper, press_track_new.issue.num, press_track_new.issue.creation, press_track_new.issue.label) VALUES (%d, %d, '%s', '%s')", $idpaper, $value, $creation, $label." (".($total+$value)."-".$value.")");
		else if ($mode == "+")
			$sql = sprintf("INSERT INTO press_track_new.delivery (press_track_new.delivery.paper, press_track_new.delivery.num, press_track_new.delivery.creation, press_track_new.delivery.invoice, press_track_new.delivery.supplier) VALUES (%d, %d, '%s', '%s', '%s')", $idpaper, $value, $creation, $label." (".($total-$value)."+".$value.")", $label);
		
		$query = mysql_query($sql);
		$idissue = mysql_insert_id(); 
		if (mysql_errno()) return mysql_errno() . ": " . mysql_error();
		else return "successful";
	}
	
	function updateDelivery($iddelivery, $param, $value) {
		if ($param == "num")
		{
			$sql = sprintf("SELECT num as val, paper as idpaper FROM press_track_new.delivery WHERE iddelivery = %d", $iddelivery);
			$query = mysql_query($sql);
			if (mysql_errno()) return mysql_errno() . ": " . mysql_error();
			$res = mysql_fetch_object($query);
			$cor_val = $value - $res->val;
			$sql = sprintf("UPDATE press_track_new.paper SET total = total + %d WHERE idpaper = %d", $cor_val, $res->idpaper);
			$query = mysql_query($sql);
			if (mysql_errno()) return mysql_errno() . ": " . mysql_error();
			$sql = sprintf("UPDATE press_track_new.delivery SET %s = %d WHERE iddelivery = %d", $param, $value, $iddelivery);
			$query = mysql_query($sql);
			if (mysql_errno()) return mysql_errno() . ": " . mysql_error();
			else return "successful";
		}
		else if ($param == "paper")
		{
			$sql = sprintf("UPDATE press_track_new.paper SET total = total - (SELECT num FROM press_track_new.delivery WHERE iddelivery = $iddelivery) WHERE idpaper = (SELECT paper FROM press_track_new.delivery WHERE iddelivery = $iddelivery)");
			$query = mysql_query($sql);
			if (mysql_errno()) return mysql_errno() . ": " . mysql_error();
			$sql = sprintf("UPDATE press_track_new.paper SET total = total + (SELECT num FROM press_track_new.delivery WHERE iddelivery = $iddelivery) WHERE idpaper = $value");
			$query = mysql_query($sql);
			if (mysql_errno()) return mysql_errno() . ": " . mysql_error();
			$sql = sprintf("UPDATE press_track_new.delivery SET paper = %d WHERE iddelivery = %d", $value, $iddelivery);
			$query = mysql_query($sql);
			if (mysql_errno()) return mysql_errno() . ": " . mysql_error();
			else return "successful";
		}
		else
			$sql = sprintf("UPDATE press_track_new.delivery SET %s = '%s' WHERE iddelivery = %d", $param, $value, $iddelivery);
		
		$query = mysql_query($sql);
		if (mysql_errno()) return mysql_errno() . ": " . mysql_error();
		else return "successful";
	}
	
	function updateIssue($idissue, $param, $value) {
		if ($param == "num")
		{
			$sql = sprintf("UPDATE press_track_new.issue SET %s = %f WHERE idissue = %d", $param, $value, $idissue);
			$query = mysql_query($sql);
		}
		else if ($param == "paper" || $param == "request" || $param == "cost")
		{
			$sql = sprintf("UPDATE press_track_new.issue SET %s = %f WHERE idissue = %d", $param, $value, $idissue);
		}
		else
		{
			$sql = sprintf("UPDATE press_track_new.issue SET %s = '%s' WHERE idissue = %d", $param, $value, $idissue);
		}
		
		$query = mysql_query($sql);
		if (mysql_errno()) return mysql_errno() . ": " . mysql_error();
		else return "successful";
	}

	// DELETE

	function removeOrder($idorder) {
		$sql = sprintf("DELETE FROM press_track_new.order WHERE press_track_new.order.idorder = %d", $idorder);
		$query = mysql_query($sql);
	}	

	function removeProduct($id) {
		$sql = sprintf("DELETE FROM press_track_new.product WHERE idproduct = %d", $id);
		$query = mysql_query($sql);
		if (mysql_errno()) return mysql_errno() . ": " . mysql_error();		
	}

	function removeTask($id) {
		$sql = sprintf("DELETE FROM press_track_new.task WHERE idtask = %d", $id);
		$query = mysql_query($sql);
		if (mysql_errno()) return mysql_errno() . ": " . mysql_error();	
		$sql = sprintf("DELETE FROM press_track_new.relation WHERE press_track_new.relation.task_id = %d", $id);
		$query = mysql_query($sql);
		if (mysql_errno()) return mysql_errno() . ": " . mysql_error();
	}
	
	function removeRelation($id) {
		$sql = sprintf("DELETE FROM press_track_new.relation WHERE idrelation = %d", $id);
		$query = mysql_query($sql);
		if (mysql_errno()) return mysql_errno() . ": " . mysql_error();		
	}	
	
	function removeOrderGroup($idorder, $cur_group, $total_group) {
		$sql = "DELETE FROM press_track_new.product WHERE press_track_new.product.order = $idorder AND press_track_new.product.group = $cur_group";
		$query = mysql_query($sql);
		
		if ($cur_group < $total_group)
		{
			$next = $cur_group + 1;
			for ($i = $next; $i < $total_group + 1; $i++)
			{
				$sql = "UPDATE press_track_new.product SET press_track_new.product.group = (press_track_new.product.group - 1) WHERE press_track_new.product.order = $idorder AND press_track_new.product.group = $i";
				$query = mysql_query($sql);
			}
		}
	}
	
	function removeIssue($id) {
		$sql = sprintf("DELETE FROM press_track_new.issue WHERE idissue = %d", $id);
		$query = mysql_query($sql);
		if (mysql_errno()) return mysql_errno() . ": " . mysql_error();	
		else return "successful"; 
	}	
}
?>